package com.dony.shop.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dony.common.utils.StringUtils;
import com.dony.common.utils.bean.BeanUtils;
import com.dony.shop.domain.Item;
import com.dony.shop.domain.ItemModel;
import com.dony.shop.domain.ShopeeShop;
import com.dony.shop.domain.vo.ItemPriceVo;
import com.dony.shop.domain.vo.PriceVo;
import com.dony.shop.mapper.ItemMapper;
import com.dony.shop.service.IItemModelService;
import com.dony.shop.service.IItemService;
import com.dony.shop.service.IShopeeShopService;
import com.dony.shop.util.ShopeeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 全球商品业务层处理
 *
 * @author sundw
 * @date 2022-03-08
 */
@Slf4j
@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Autowired
    ShopeeUtil shopeeUtil;

    @Resource
    IShopeeShopService shopService;

    @Resource
    IItemModelService itemModelService;

    @Resource
    ThreadPoolTaskExecutor executor;


    /**
     * 置顶商品
     */
    public void boostItemTask() {
        //获取需要boost的店铺
        List<ShopeeShop> shopList = shopService.list(new QueryWrapper<ShopeeShop>().eq("is_publish", true));
        for (ShopeeShop shop : shopList) {
            //获取产品列表
            try {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("page_size", 40);
                paramMap.put("offset", 0);
                paramMap.put("item_status", "NORMAL");
                JSONObject response = shopeeUtil.shopGetHandler("/api/v2/product/get_item_list", shop.getShopId(), paramMap);
                if (response == null) {
                    continue;
                }
                List<JSONObject> itemList = response.getList("item", JSONObject.class);
                for (int i = 0; i < 5; i++) {
                    Map<String, Object> paramMap1 = new HashMap<>();
                    paramMap1.put("item_id_list", new long[]{itemList.get(RandomUtil.randomInt(NumberUtil.min(itemList.size(), 39))).getLong("item_id")});
                    JSONObject response1 = shopeeUtil.shopPostHandler("/api/v2/product/boost_item", shop.getShopId(), paramMap1);
                    if (response1 != null) {
                        log.info("店铺：{}置顶成功！", shop.getShopName());
                    }
                }
            } catch (Exception e) {
                log.error("店铺：{}置顶失败！", shop.getShopName());
            }
        }
    }

    @Override
    public List<Item> getListByParam(Item item) {

        LambdaQueryWrapper<Item> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Item::getMerchantId, item.getMerchantId());
        if (StringUtils.isNotEmpty(item.getItemName())) {
            wrapper.and(w -> {
                w.eq(Item::getItemId, item.getItemName())
                        .or()
                        .like(Item::getItemName, item.getItemName());
            });
        }
        wrapper.orderByDesc(Item::getUpdateTime);
        List<Item> itemList = this.list(wrapper);
        if (itemList == null || itemList.size() == 0) return null;
        itemList.forEach(ite -> {
            List<ItemModel> itemModelList = itemModelService.list(new QueryWrapper<ItemModel>().eq("item_id", ite.getItemId()));
            ite.setItemModelList(itemModelList);
        });
        return itemList;
    }

    @Override
    public Item getItemWithPrice(Long itemId) {
        Item item = this.getById(itemId);
        if (item == null) {
            return null;
        }
        String currency = "";
        List<ItemModel> itemModels = itemModelService.list(new QueryWrapper<ItemModel>().eq("item_id", itemId));
        Map<Float, Float> priceMap = new HashMap<>();
        for (ItemModel model : itemModels) {
            currency = model.getCurrency();
            Float aFloat = priceMap.get(model.getOriginalPrice());
            if (aFloat == null) {
                priceMap.put(model.getOriginalPrice(), model.getCurrentPrice());
            }
        }
        itemModels.clear();
        for (Map.Entry<Float, Float> entry : priceMap.entrySet()) {
            ItemModel im = new ItemModel();
            im.setOriginalPrice(entry.getKey());
            im.setCurrentPrice(entry.getValue());
            try {
                im.setInflatedPriceOfOriginalPrice(Float.valueOf(item.getItemSku()));
            } catch (Exception e) {
                //log.error("无法转换字符");
            }
            im.setInflatedPriceOfCurrentPrice(item.getWeight());
            im.setCurrency(currency);
            im.setItemId(itemId);
            itemModels.add(im);
        }
        item.setItemModelList(itemModels);
        return item;
    }

//    @Override
//    public Item getItemWithPrice(Long itemId) {
//        Item item = this.getById(itemId);
//        if (item == null) {
//            return null;
//        }
//        ItemPriceVo priceVo = new ItemPriceVo();
//        BeanUtils.copyProperties(item,priceVo);
//        List<ItemModel> itemModels = itemModelService.list(new QueryWrapper<ItemModel>().eq("item_id", itemId));
//        Map<Float, Float> priceMap = new HashMap<>();
//        for (ItemModel model : itemModels) {
//            Float aFloat = priceMap.get(model.getOriginalPrice());
//            if (aFloat == null) {
//                priceMap.put(model.getOriginalPrice(), model.getCurrentPrice());
//                PriceVo vo = new PriceVo();
//                vo.setGlobalItemId(item.getGlobalProductId());
//
//                vo.setGlobalPrice();
//                vo.setOrigenPrice(model.getCurrentPrice());
//                vo.setWeight();
//
//            }
//        }
//
//
//        itemModels.clear();
//        for (Map.Entry<Float, Float> entry : priceMap.entrySet()) {
//            Float key = entry.getKey();
//            Float value = entry.getValue();
//            ItemModel im = new ItemModel();
//            im.setOriginalPrice(key);
//            im.setCurrentPrice(value);
//            itemModels.add(im);
//        }
//        item.setItemModelList(itemModels);
//        return item;
//    }


    @Override
    public void syncShopItemByShopId(Long tenantId, Long merchaintId, Long shopId) {
        //前期先统一的使用删除的方式
        this.remove(new QueryWrapper<Item>().eq("shop_id", shopId));
        Boolean hasNextPage = false;
        Integer offset = 0;
        do {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("offset", offset);
            paramMap.put("page_size", 100);
            paramMap.put("item_status", Arrays.asList("NORMAL", "BANNED", "DELETED", "UNLIST"));
            JSONObject response = shopeeUtil.shopGetHandler("/api/v2/product/get_item_list", shopId, paramMap);//DELETED
            if (response == null) continue;
            hasNextPage = response.getBoolean("has_next_page");
            offset = response.getInteger("next_offset");
            List<JSONObject> itemList = response.getList("item", JSONObject.class);
            List<Item> shopItems = itemList.stream().map(item -> {
                //前期先统一的使用删除的方式
                itemModelService.remove(new QueryWrapper<ItemModel>().eq("item_id", item.getLong("item_id")));
                Item shopItem = new Item();
                shopItem.setShopId(shopId);
                shopItem.setTenantId(tenantId);
                shopItem.setMerchantId(merchaintId);
                shopItem.setItemId(item.getLong("item_id"));
                //shopItem.setCategoryId(item.getLong("category_id"));
                //shopItem.setItemName(item.getString("item_name"));
                //shopItem.setImage((String) item.getJSONObject("image").getJSONArray("image_url_list").get(0));
                //shopItem.setCreateTime(new Date(item.getLong("create_time") * 1000L));
                shopItem.setUpdateTime(new Date(item.getLong("update_time") * 1000L));
                shopItem.setGlobalProductId(this.getGlobalProductIdByItemId(merchaintId, shopId, item.getLong("item_id")));
                shopItem.setItemStatus(item.getString("item_status"));
                //保存型号
                itemModelService.syncModel(shopItem.getShopId(), shopItem.getItemId());
                return shopItem;
            }).collect(Collectors.toList());
            this.saveBatch(shopItems);
        } while (hasNextPage);
        log.info("--->店铺商品状态更新完成:{}的全部信息更新完成", shopId);
    }


    @Override
    public Long getGlobalProductIdByItemId(Long merchantId, Long shopId, Long itemId) {
        if (merchantId == null) {
            return null;
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("shop_id", shopId);
        paramMap.put("item_id_list", Arrays.asList(itemId));
        JSONObject response = shopeeUtil.merchantGetHandler("/api/v2/global_product/get_global_item_id", merchantId, paramMap);
        if (response == null) return null;
        List<JSONObject> itemIdMap = response.getList("item_id_map", JSONObject.class);
        return itemIdMap.get(0).getLong("global_item_id");

    }


    @Override
    public Item syncShopItemByItemId(Long shopId, Long itemId) {
        ShopeeShop shop = shopService.getByShopId(shopId);
        return syncShopItemByItemId(shop.getTenantId(), shop.getMerchantId(), shopId, itemId);
    }

    @Override
    public Item syncShopItemByItemId(Long tenantId, Long merchantId, Long shopId, Long itemId) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("item_id_list", Arrays.asList(itemId));
        JSONObject response = shopeeUtil.shopGetHandler("/api/v2/product/get_item_base_info", shopId, paramMap);
        if (response != null) {
            List<JSONObject> itemList = response.getList("item_list", JSONObject.class);
            List<Item> shopItems = itemList.stream().map(item -> {
                Item shopItem = new Item();
                shopItem.setShopId(shopId);
                shopItem.setItemId(item.getLong("item_id"));
                shopItem.setCategoryId(item.getLong("category_id"));
                shopItem.setItemName(item.getString("item_name"));
                shopItem.setCreateTime(new Date(item.getLong("create_time") * 1000L));
                shopItem.setUpdateTime(new Date(item.getLong("update_time") * 1000L));
                shopItem.setItemStatus(item.getString("item_status"));
                shopItem.setItemSku(item.getString("item_sku"));
                shopItem.setWeight(item.getFloat("weight"));
                shopItem.setTenantId(tenantId);
                shopItem.setMerchantId(merchantId);
                shopItem.setImage((String) item.getJSONObject("image").getJSONArray("image_url_list").get(0));
                shopItem.setGlobalProductId(this.getGlobalProductIdByItemId(merchantId, shopId, item.getLong("item_id")));
                List<JSONObject> priceInfo = item.getList("price_info", JSONObject.class);
                if (priceInfo != null && priceInfo.size() > 0) {
                    shopItem.setCurrency(priceInfo.get(0).getString("currency"));
                }
                shopItem.setItemStatus(item.getString("item_status"));
                //保存型号
                itemModelService.syncModel(shopItem.getShopId(), shopItem.getItemId());
                return shopItem;
            }).collect(Collectors.toList());
            if (shopItems != null && shopItems.size() != 0) {
                this.saveOrUpdate(shopItems.get(0));
                return shopItems.get(0);
            }
        }
        return null;
    }


    @Override
    public Boolean syncItemStatusByMerchant(Long merchantId) {
        List<ShopeeShop> publishShops = shopService.getPublishShopListByMerchant(merchantId);
        publishShops.forEach(shop -> {
            this.syncShopItemByShopId(shop.getTenantId(), shop.getMerchantId(), shop.getShopId());
        });
        return true;
    }


}
